'use strict';
angular.module("App")
    .controller('mailTabCtrl',['$scope','menu',function($scope,menu){
         //设置二级菜单
        $scope.subMenu = menu;

    }])
    .controller('sendMailCtrl', ['$scope','$rootScope', 'mailService','smsService','ngVerify','growlService','Upload','apiService','cookie', function ($scope,$rootScope, mailService,smsService,ngVerify,growlService,Upload,apiService,cookie) {
        //发送邮件
        $scope.persons = [];   //获取选择发送通信录
        $scope.select_all = false; //默认不选中
        $scope.vm = {};   //进度条
        var item = {};    //收件人员
        $scope.fujians = [];  //附件内容
        $scope.sendMail = {};  //发送邮件字段

        //获取树
        $scope.treeOptions = {
            nodeChildren: "children",
            dirSelectable: false,
            multiSelection: true,
            injectClasses: {
                ul: "a1",
                li: "a2",
                liSelected: "a7",
                iExpanded: "a3",
                iCollapsed: "a4",
                iLeaf: "a5",
                label: "a6",
                labelSelected: "a8"
            }
        }

        //获取通信录数据
        smsService.getSmsPhone(
        ).then(function (data) {
            $scope.dataForTheTree = data;
            $scope.dataForTheTree.state = false;
        }, function (error) {
            alert("Fail: " + error);
        })
        //全选
        $scope.selectAll = function () {
            if ($scope.select_all) {
                item = {};
                angular.forEach($scope.dataForTheTree, function (i) {
                   i.state = true;
                    if (!angular.equals([], i.children)) {
                        angular.forEach(i.children, function (j) {
                            item = {
                                Username: j.UserName,
                                UserID: j.UserID,
                                Phone: j.Phone
                            }
                            $scope.persons.push(item);
                            j.state = true;
                        });
                    }
                })
            } else {
                angular.forEach($scope.dataForTheTree, function (i) {
                    i.state = false;
                    if (!angular.equals([], i.children)) {
                        angular.forEach(i.children, function (j) {
                            $scope.persons = [];
                            j.state = false;
                        });
                    }
                })
            }


        }

        //单选，多选
        $scope.showSelected = function (node, selected, $parentNode, $index) {
            var sel = 0;    //选中的checkbox
            var count = 0;  //总checkbox
            //选中
            if (node.state) {
                //根节点
                if (node.children !== undefined) {
                    //根节点选中且包含元素
                    if (!angular.equals([], node.children)) {
                        angular.forEach(node.children, function (i) {
                            if (findIndex(i.UserID) == -1) {
                                item = {
                                    Username: i.UserName,
                                    UserID: i.UserID,
                                    Phone: i.Phone
                                }
                                $scope.persons.push(item);
                                i.state = true;
                            }

                        });
                    }
                }
                //元素
                else {
                    if (findIndex(node.UserID) == -1) {
                        item = {
                            Username: node.UserName,
                            UserID: node.UserID,
                            Phone: node.Phone
                        }
                        $scope.persons.push(item);
                        node.state = true;
                        $parentNode.state = true;
                    }
                    angular.forEach($parentNode.children, function (i) {
                        if (!i.state) {
                            $parentNode.state = false;
                            return;
                        }
                    });
                }

            }
            //未选中
            else {
                //取消根节点选中
                if (node.children !== undefined) {
                    //根节点选中且包含元素
                    if (!angular.equals([], node.children)) {
                        angular.forEach(node.children, function (i) {
                            var index = findIndex(i.UserID);
                            if (index != -1) {
                                $scope.persons.splice(index, 1);
                                i.state = false;
                            }
                        });
                    }
                }
                //取消元素选中
                else {
                    var index = findIndex(node.UserID);
                    if (index != -1) {
                        $scope.persons.splice(index, 1);
                        node.state = false;
                    }
                    $parentNode.state = false;
                }

            }
            //全选与取消全选
            angular.forEach($scope.dataForTheTree, function (i) {
                if(i.state){
                    sel++;
                }
                count++;
            })
            if(sel === count){
               $scope.select_all = true;
            }else{
               $scope.select_all = false;
            }

        };

        //发现选择项目
        var findIndex = function (UserID) {
            var index = -1;
            angular.forEach($scope.persons, function (item, key) {
                if (item.UserID == UserID) {
                    index = key;
                    return;
                }
            });
            return index;
        };

        //删除选中项目
        $scope.selDel = function (ev, id) {
            //阻止元素发生默认行为
            ev.preventDefault();
            angular.forEach($scope.persons, function (item, key) {
                if (item.UserID == id) {
                    $scope.persons.splice(key, 1);
                    return;
                }
            });
            angular.forEach($scope.dataForTheTree, function (i) {
                if (!angular.equals([], i.children)) {
                    angular.forEach(i.children, function (j) {
                        if(j.UserID == id){
                            j.state = false;
                            i.state =false;
                            $scope.select_all =false;
                            return;
                        }
                    });
                }
            })
        }

        //发送邮件
        $scope.submitForm = function () {
            //返回所有未验证通过的表单元素，并标记
            ngVerify.check('mailForm',function (errEls) {
                if(angular.equals([], errEls)){
                    if(angular.equals([],$scope.persons)){
                        growlService.growl('请选择收件人!', 'danger');
                    }else{
                       console.log("发送成功");
                       var tos = [];
                        angular.forEach($scope.persons, function (item) {
                            tos.push(item.UserID);
                        });
                     //   收件人：Tos 格式：用户ID,用户ID，标题：Title，内容：Brief,附件：InfosCommAttachs 默认:""
                        mailService.sendMail(
                            {
                                Tos : tos.join(","),        //收件人
                                Title : $scope.sendMail.title,         //标题
                                Brief : $scope.sendMail.content,       //内容
                                InfosCommAttachs : $scope.fujians      //附件
                            }
                        ).then(function (data) {
                            console.log(JSON.stringify($scope.fujians));
                        }, function (error) {
                            alert("Fail: " + error);
                        })
                    }
                }
            });
        }

        //上传附件
        $scope.openUploadAttachModal = function() {
            var modal = $rootScope.openContentModal('uploadAttachModal','');
            modal.result.then(function(file) {
                $scope.uploadFile(file);
            });
        };

        //上传服务
        $scope.uploadFile = function (file) {
            var upload = Upload.upload({
                //服务端接收
                url: apiService.uploadUrl,
                //上传的同时带的参数
                data: {"blackbox" : cookie.getjm()},
                //上传的文件
                file: file
            })

            upload.then(function(resp) {
                // 文件上传成功
                var item = {
                    FileName : resp.data.UploadDataModelList[0].FileName,
                    FilePath : resp.data.UploadDataModelList[0].FilePath
                }
                $scope.fujians.push(item);
                console.log('file ' + resp.config.data.file.name + 'is uploaded successfully. Response: ' + resp.data);
                console.log($scope.fujians);
            }, function(resp) {
                // 处理错误
            }, function(evt) {
                $scope.vm.showProgress = true;
                $scope.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            });

            upload.catch(function(error){
                //捕获异常
            })
            upload.finally(function(res){
                $scope.vm.showProgress = false;
            }, function(notify){
                //console.log(notify);
            });

        };


    }])
    .controller('receiveMailCtrl', ['$rootScope', '$scope', 'mailService', function ($rootScope, $scope, mailService) {
        //接收邮件
        $scope.receiveData = [];  //数据集
        $scope.totalItems = 0;    //总条数默认0
        $scope.IsView = null;     //读取状态，已读，未读
        $scope.collection = [];   //选中的集合
        $scope.select_all = false;  //默认不选中



        //获取数据
        $scope.getData = function (isview,page) {
            mailService.receiveMailList(
                {
                    IsView: isview,  //2代表全部 0 代表未发送 1 代表已发送
                    page: page,
                    rows: $rootScope.appConfig.rows
                }
            ).then(function (data) {
                console.log(data);
                $scope.receiveData = data.NewsTempList;
                $scope.totalItems = data.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })
        }
        //页面初始化
        $scope.getData($scope.IsView,1);

        //页面改变时触发事件
        $scope.pageChanged = function () {
            $scope.getData($scope.IsView,$scope.currentPage);
        }

        //状态改变
        $scope.change = function () {
            $scope.getData($scope.IsView,1);

        }
        //全选
        $scope.selectAll = function () {
            $scope.collection = mailService.selectAll($scope.select_all,$scope.receiveData);
        };

        //单选或多选
        $scope.selectOne = function () {
            angular.forEach($scope.receiveData, function (i) {
                var index = $scope.collection.indexOf(i.ID);
                if (i.checked && index === -1) {
                    $scope.collection.push(i.ID);
                } else if (!i.checked && index !== -1) {
                    $scope.collection.splice(index, 1);
                }
                ;
            })

            if ($scope.receiveData.length === $scope.collection.length) {
                $scope.select_all = true;
            } else {
                $scope.select_all = false;
            }
        }


        //批量删除操作
        $scope.deleteSelect = function () {
            // 操作CURD
            if ($scope.collection[0] == "" || $scope.collection.length == 0) {//没有选择一个的时候提示
                alert("请至少选中一条数据在操作！")
                return;
            }
            else {
                $rootScope.showConfirm("确定要删除吗?").then(function () {
                    mailService.batchDelete({
                        IDs: $scope.collection.join(",")
                    })
                        .then(function (data) {
                            if (!data.errCode) {

                                growlService.growl('删除成功!', 'danger');
                                $scope.select_all = false;
                                $scope.collection = [];
                                $scope.getData($scope.IsView,$scope.currentPage || 1);
                            }
                        });
                });

            }
        }

        //单个删除
        $scope.rmMail = function (ev, id) {
            //阻止元素发生默认行为
            ev.preventDefault();
            $rootScope.showConfirm("确定要删除吗?").then(function () {
                //删除数据
                mailService.delete(
                    {
                        ID: id
                    }
                ).then(function (res) {
                    //$rootScope.tips.showSuccess("删除成功");
                    growlService.growl('删除成功!', 'danger');
                    //$state.reload();
                    $scope.getData($scope.IsView,$scope.currentPage || 1);
                }, function (error) {
                    alert("Fail: " + error);
                })
            });
        }


    }])
    .controller('publicMailCtrl', ['$rootScope', '$scope', 'mailService','growlService', function ($rootScope, $scope, mailService,growlService) {
        //公共邮件
        $scope.receiveData = [];  //数据集
        $scope.totalItems = 0;    //总条数默认0
        $scope.IsView = null;     //读取状态，已读，未读
        $scope.collection = [];   //选中的集合
        $scope.select_all = false;  //默认不选中



        //获取数据
        $scope.getData = function (isview,page) {
            mailService.publicMailList(
                {
                    IsView: isview,  //2代表全部 0 代表未发送 1 代表已发送
                    page: page,
                    rows: $rootScope.appConfig.rows
                }
            ).then(function (data) {
                console.log(data);
                $scope.receiveData = data.PublicMailList;
                $scope.totalItems = data.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })
        }
        //页面初始化
        $scope.getData($scope.IsView,1);

        //页面改变时触发事件
        $scope.pageChanged = function () {
            $scope.getData($scope.IsView,$scope.currentPage);
        }

        //状态改变
        $scope.change = function () {
            $scope.getData($scope.IsView,1);

        }
        //全选
        $scope.selectAll = function () {
            $scope.collection = mailService.selectAll($scope.select_all,$scope.receiveData);
        };

        //单选或多选
        $scope.selectOne = function () {
            angular.forEach($scope.receiveData, function (i) {
                var index = $scope.collection.indexOf(i.ID);
                if (i.checked && index === -1) {
                    $scope.collection.push(i.ID);
                } else if (!i.checked && index !== -1) {
                    $scope.collection.splice(index, 1);
                }
                ;
            })

            if ($scope.receiveData.length === $scope.collection.length) {
                $scope.select_all = true;
            } else {
                $scope.select_all = false;
            }
            console.log($scope.collection);
        }


        //批量删除操作
        $scope.deleteSelect = function () {
            // 操作CURD
            if ($scope.collection[0] == "" || $scope.collection.length == 0) {//没有选择一个的时候提示
                alert("请至少选中一条数据在操作！")
                return;
            }
            else {
                $rootScope.showConfirm("确定要删除吗?").then(function () {
                    mailService.batchDelete({
                        IDs: $scope.collection.join(",")
                    })
                        .then(function (data) {
                            if (!data.errCode) {

                                growlService.growl('删除成功!', 'danger');
                                $scope.select_all = false;
                                $scope.collection = [];
                                $scope.getData($scope.IsView,$scope.currentPage || 1);
                            }
                        });
                });

            }
        }

        //单个删除
        $scope.rmMail = function (ev, id) {
            //阻止元素发生默认行为
            ev.preventDefault();
            $rootScope.showConfirm("确定要删除吗?").then(function () {
                //删除数据
                mailService.delete(
                    {
                        ID: id
                    }
                ).then(function (res) {
                    //$rootScope.tips.showSuccess("删除成功");
                    growlService.growl('删除成功!', 'danger');
                    //$state.reload();
                    $scope.getData($scope.IsView,$scope.currentPage || 1);
                }, function (error) {
                    alert("Fail: " + error);
                })
            });
        }


    }])
    .controller('completedMailCtrl', ['$rootScope', '$scope','$state','$timeout','mailService','growlService','cfpLoadingBar', function ($rootScope, $scope,$state,$timeout,mailService,growlService,cfpLoadingBar) {
        //已发送邮件
        $scope.receiveData = [];    //数据集
        $scope.totalItems = 0;      //总条数默认0
        $scope.IsView = null;       //读取状态，已读，未读
        $scope.collection = [];     //选中的集合
        $scope.select_all = false;  //默认不选中

        $scope.start = function() {
            cfpLoadingBar.start();
        };

        $scope.complete = function () {
            cfpLoadingBar.complete();
        };


        $scope.getData = function (isview,page) {
            mailService.completedMailList(
                {
                    IsView: isview,  //2代表全部 0 代表未发送 1 代表已发送
                    page: page,
                    rows: $rootScope.appConfig.rows
                }
            ).then(function (data) {
                /*$timeout(function() {

                }, 2000);*/
                $scope.receiveData = data.MailSendModelList;
                $scope.totalItems = data.totalRows;

            }, function (error) {
                alert("Fail: " + error);
            })
        };
        //页面初始化
        $scope.getData($scope.IsView,1);

        //页面改变时触发事件
        $scope.pageChanged = function () {
            $scope.getData($scope.IsView,$scope.currentPage);
        }

        //状态改变
        $scope.change = function () {
            $scope.getData($scope.IsView,1);
        }

        //单个删除
        $scope.rmMail = function (ev, id) {
            //阻止元素发生默认行为
            ev.preventDefault();
            $rootScope.showConfirm("确定要删除吗?").then(function () {
                //删除数据
                mailService.delete(
                    {
                        ID: id
                    }
                ).then(function (res) {
                    //$rootScope.tips.showSuccess("删除成功");
                    growlService.growl('删除成功!', 'danger');
                    //$state.reload();
                    $scope.getData($scope.IsView,$scope.currentPage || 1);
                }, function (error) {
                    alert("Fail: " + error);
                })
            });
        }


        //全选
        $scope.selectAll = function () {
            $scope.collection = mailService.selectAll($scope.select_all,$scope.receiveData);
        };


        //单选、多选
        $scope.selectOne = function () {
            angular.forEach($scope.receiveData, function (i) {
                var index = $scope.collection.indexOf(i.ID);
                if (i.checked && index === -1) {
                    $scope.collection.push(i.ID);
                } else if (!i.checked && index !== -1) {
                    $scope.collection.splice(index, 1);
                }
            })

            if ($scope.receiveData.length === $scope.collection.length) {
                $scope.select_all = true;
            } else {
                $scope.select_all = false;
            }
        }

        //批量删除操作
        $scope.deleteSelect = function () {
            // 操作CURD
            if ($scope.collection[0] == "" || $scope.collection.length == 0) {//没有选择一个的时候提示
                alert("请至少选中一条数据在操作！")
                return;
            }
            else {
                $rootScope.showConfirm("确定要删除吗?").then(function () {
                    mailService.batchDelete({
                        IDs: $scope.collection.join(",")
                    })
                        .then(function (data) {
                            if (!data.errCode) {

                                growlService.growl('删除成功!', 'danger');
                                $scope.select_all = false;
                                $scope.collection = [];
                                $scope.getData($scope.IsView,$scope.currentPage || 1);
                            }
                        });
                });

            }
        }



    }])
    .controller('chaMailCtrl', ['$rootScope', '$scope','$stateParams','mailService', function ($rootScope, $scope,$stateParams,mailService) {
        //获取数据
        mailService.cha(
            {
                ID: $stateParams.ID
            }
        ).then(function (res) {
            $scope.mailContent = res.InfosCommInfo;
            if(!res.InfosCommInfo.IsView){
                mailService.changeStatus(
                    {
                        ID: $stateParams.ID
                    }
                ).then(function (res) {
                    return res;
                }, function (error) {
                    return error;
                })
            }
        }, function (error) {
            alert("Fail: " + error);
        })
    }])
    .controller('ceshiCtrl',['$scope','cookie','auth',function($scope,cookie,auth){
        $scope.toggleLoad=function(){
           $scope.beginLoading=true;
        };
    }])







